package cn.kgc.dao.impl;

import cn.kgc.dao.RoleDao;
import cn.kgc.pojo.Role;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

/**
 * dao层接口的实现类
 */
@Repository("roleDao")
public class RoleDaoImpl implements RoleDao {

    /**
     * 创建QUeryRunner对象执行sql语句
     * 执行查询:query()
     * 增删改:update()
     */
    @Autowired
    private QueryRunner queryRunner;

    /**
     * 查询所有角色
     *
     * @return
     */
    public List<Role> getAllRole() throws SQLException {
        return queryRunner.query("select * from smbms_role",new BeanListHandler<Role>(Role.class));
    }

    /**
     * 根据id查询角色
     *
     * @param id
     * @return
     */
    public Role getRoleById(Integer id) throws SQLException {
        List<Role> roleList= queryRunner.query("select * from smbms_role where id=?",new BeanListHandler<Role>(Role.class),id);
        if(roleList.size()==0){
            return null;
        }else{
            return roleList.get(0);
        }
    }

    /**
     * 添加角色
     *
     * @param role
     * @return
     */
    public Integer addRole(Role role) throws SQLException {
        return queryRunner.update("insert into smbms_role(roleCode, roleName, createdBy, creationDate) VALUES(?,?,?,?) ",role.getRoleCode(),role.getRoleName(),role.getCreatedBy(),role.getCreationDate());

    }

    /**
     * 修改角色
     *
     * @param role
     * @return
     */
    public Integer updateRole(Role role) throws SQLException {
        return queryRunner.update("update smbms_role set roleName=? where id=?",role.getRoleName(),role.getId());
    }

    /**
     * 删除角色
     *
     * @param id
     * @return
     */
    public Integer delRole(Integer id) throws SQLException {
        return queryRunner.update("delete from smbms_role where id=?",id);

    }
}
